﻿using WeiXin.Base.Pay.Lib;

namespace WeiXin.Base.Pay
{
    using System;
    using System.Web;

    /// <summary>
    /// 扫码支付模式一回调处理类
    /// 接收微信支付后台发送的扫码结果，调用统一下单接口并将下单结果返回给微信支付后台
    /// </summary>
    public class NativeNotify : WxPayNotify
    {
        public override void ProcessNotify()
        {
            if (null == InitEvent)
            {
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "获取订单事件未设置");
                WxPayLog.Info(this.GetType().ToString(), "The data WeChat post is error : " + res.ToXml());
                HttpContext.Current.Response.Write(res.ToXml());
                HttpContext.Current.Response.End();
            }
            WxPayData notifyData = GetNotifyData();

            //检查openid和product_id是否返回
            if (!notifyData.IsSet("openid") || !notifyData.IsSet("product_id"))
            {
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "回调数据异常");
                WxPayLog.Info(this.GetType().ToString(), "The data WeChat post is error : " + res.ToXml());
                HttpContext.Current.Response.Write(res.ToXml());
                HttpContext.Current.Response.End();
            }

            //调统一下单接口，获得下单结果
            string openid = notifyData.GetValue("openid").ToString();
            string product_id = notifyData.GetValue("product_id").ToString();
            WxPayData unifiedOrderResult = new WxPayData();
            try
            {
                unifiedOrderResult = UnifiedOrder(openid, product_id);
            }
            catch//若在调统一下单接口时抛异常，立即返回结果给微信支付后台
            {
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "统一下单失败");
                WxPayLog.Error(this.GetType().ToString(), "UnifiedOrder failure : " + res.ToXml());
                HttpContext.Current.Response.Write(res.ToXml());
                HttpContext.Current.Response.End();
            }

            //若下单失败，则立即返回结果给微信支付后台
            if (!unifiedOrderResult.IsSet("appid") || !unifiedOrderResult.IsSet("mch_id") || !unifiedOrderResult.IsSet("prepay_id"))
            {
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "统一下单失败");
                WxPayLog.Error(this.GetType().ToString(), "UnifiedOrder failure : " + res.ToXml());
                HttpContext.Current.Response.Write(res.ToXml());
                HttpContext.Current.Response.End();
            }

            //统一下单成功,则返回成功结果给微信支付后台
            WxPayData data = new WxPayData();
            data.SetValue("return_code", "SUCCESS");
            data.SetValue("return_msg", "OK");
            data.SetValue("appid", WxPayConfig.APPID);
            data.SetValue("mch_id", WxPayConfig.MCHID);
            data.SetValue("nonce_str", WxPayApi.GenerateNonceStr());
            data.SetValue("prepay_id", unifiedOrderResult.GetValue("prepay_id"));
            data.SetValue("result_code", "SUCCESS");
            data.SetValue("err_code_des", "OK");
            data.SetValue("sign", data.MakeSign());

            WxPayLog.Info(this.GetType().ToString(), "UnifiedOrder success , send data to WeChat : " + data.ToXml());
            HttpContext.Current.Response.Write(data.ToXml());
            HttpContext.Current.Response.End();
        }

        private WxPayData UnifiedOrder(string openId, string productId)
        {
            int total_fee = 0;
            string out_trade_no = "", body = "", goods_tag = "", attach = "";
            OnInit(productId, out out_trade_no, out total_fee, out body, out goods_tag, out attach);
            //统一下单
            WxPayData req = new WxPayData();
            req.SetValue("body", body);
            req.SetValue("attach", attach);
            req.SetValue("out_trade_no", out_trade_no);
            req.SetValue("total_fee", total_fee);
            req.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
            req.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));
            req.SetValue("goods_tag", goods_tag);
            req.SetValue("trade_type", "NATIVE");
            req.SetValue("openid", openId);
            req.SetValue("product_id", productId);
            WxPayData result = WxPayApi.UnifiedOrder(req);
            return result;
        }

        /// <summary>
        /// 获取订单或商品委托
        /// </summary>
        ///  <param name="productId">商品ID（订单中包含的商品ID）</param>
        /// <param name="out_trade_no">商户订单号（建议根据当前系统时间加随机序列来生成订单号）</param>
        /// <param name="total_fee">订单总金额(单位：分)</param>
        /// <param name="body">商品或支付单简要描述</param>
        /// <param name="goods_tag">商品标记，代金券或立减优惠功能的参数</param>
        /// <param name="attach">订单附加数据(在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据)</param> 
        public delegate void InitProductHandler(string productId, out string out_trade_no, out int total_fee, out string body, out string goods_tag, out string attach);

        /// <summary>
        /// 获取订单或商品事件
        /// </summary>
        /// <param name="productId">商品ID（订单中包含的商品ID）</param>
        /// <param name="out_trade_no">商户订单号（建议根据当前系统时间加随机序列来生成订单号）</param>
        /// <param name="total_fee">订单总金额(单位：分)</param>
        /// <param name="body">商品或支付单简要描述</param>
        /// <param name="goods_tag">商品标记，代金券或立减优惠功能的参数(可为空字符串)</param>
        /// <param name="attach">订单附加数据(在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据)(可为空字符串)</param> 

        public event InitProductHandler InitEvent;

        /// <summary>
        /// 必须执行获取商品或订单事件
        /// </summary>
        /// <param name="productId">商品ID（订单中包含的商品ID）</param>
        /// <param name="out_trade_no">商户订单号（建议根据当前系统时间加随机序列来生成订单号）</param>
        /// <param name="total_fee">订单总金额(单位：分)</param>
        /// <param name="body">商品或支付单简要描述</param>
        /// <param name="goods_tag">商品标记，代金券或立减优惠功能的参数(可为空字符串)</param>
        /// <param name="attach">订单附加数据(在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据)(可为空字符串)</param> 

        protected void OnInit(string productId, out string out_trade_no, out int total_fee, out string body, out string goods_tag, out string attach)
        {
            out_trade_no = body = goods_tag = attach = string.Empty;
            total_fee = 0;
            if (InitEvent != null)
            {
                InitEvent(productId, out out_trade_no, out total_fee, out body, out goods_tag, out attach);
            }
        }
    }
}